#pragma once
#include<thread>
#include<iostream>
#include<vector>
#include<mutex>
#include<atomic>//原子操作
#include<queue>
#include<functional>
#include<condition_variable>
#include<chrono>
#include<unistd.h> 
#include<map>
#include<future> //返回值类型

class ThreadPool{
    public:
    ThreadPool(int min=2,int max=16); //std::thread::hardware_concurrency()

    ~ThreadPool();


    void addTaks(std::function<void()> task);

    // template<typename F,typename... Args>
    // auto addTaks(F&& f,Args&&... args)->std::future<typename std::result_of<F(Args...)>::type>
    // {
    //     //package_task
    //     using returnType=typename std::result_of<F(Args...)>::type;
    //     auto mytask=std::make_shared<std::packaged_task<returnType()>>(
    //         std::bind(std::forward<F>(f),std::forward<Args>(args)...)
    //     );
    //     //get future
    //     std::future<returnType> res= mytask->get_future();
    //     //package_task包装的任务函数添加到任务队列
    //     m_queuemutex.lock();
    //     m_taskqueue.emplace([mytask](){(*mytask)();});
    //     m_queuemutex.unlock();
    //     m_cond.notify_one();
    //     return res;
    // }
    private:
    void manager(void);
    void worker(void);
    private:
    std::thread * m_manager;
    std::map<std::thread::id,std::thread> m_workers;
    std::vector<std::thread::id> m_exitthreadid;
    std::atomic<int> m_maxthread;
    std::atomic<int> m_minthread;
    std::atomic<int> m_curthread; //当前线程数量
    std::atomic<int> m_idlethread; //当前空闲线程数量
    std::atomic<int> m_exitthread; //当前退出线程数量
    std::atomic<bool> m_stop; //是否停止
    std::queue<std::function<void()>> m_taskqueue; //任务队列
    std::mutex m_queuemutex; //互斥锁
    std::mutex m_idsmutex;
    std::condition_variable m_cond; //条件变量 
};